package com.tzsp.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tzsp.reggie.commons.contans.R;
import com.tzsp.reggie.commons.dto.DishDto;
import com.tzsp.reggie.domain.Category;
import com.tzsp.reggie.domain.Dish;
import com.tzsp.reggie.domain.DishFlavor;
import com.tzsp.reggie.service.CategoryService;
import com.tzsp.reggie.service.DishFlavorService;
import com.tzsp.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> addNewDishes(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());

        dishService.saveWithFlavor(dishDto);
        return R.success("菜品添加成功");
    }

    /**
     * 菜品分页查询，条件查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> dishPageQuery(int page,int pageSize,String name){
        //构造分页构造器
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dtoPage = new Page<>();

        //构造条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件，
        queryWrapper.eq(name!=null,Dish::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //执行分页查询
        dishService.page(pageInfo,queryWrapper);

        //将pageInfo中的信息复制到dtoPage中
        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        //获取records
        List<Dish> records = pageInfo.getRecords();
        //将records（变换封装后）封装到list中
        List<DishDto> list =records.stream().map((item)->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            //获取categoryId
            Long categoryId = item.getCategoryId();
            //根据categoryId查询菜品分类的categoryName
            Category category = categoryService.getById(categoryId);
            if (category!=null){
                String categoryName = category.getName();
                //将查询到的categoryName封装到dishDto的categoryName
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }

    /**
     * 根据id获取菜品和菜品的口味，展示在修改菜品页面
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> queryDishInfoById(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品信息
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> updateDish(@RequestBody DishDto dishDto){
        log.info("dishDto:{}",dishDto);
        dishService.updateWithFlavor(dishDto);
        return R.success("修改菜品成功");
    }

    /**
     * 删除菜品信息(批量or单个)
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> deleteDish(@RequestParam("ids")List<Long> ids){
        log.info("ids:{}",ids);
        dishService.deleteWithFlavor(ids);
        return R.success("删除成功");
    }

    /**
     *修改菜品的售卖状态(批量and单个)
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable("status") Integer status,@RequestParam List<Long> ids){
        //  菜品具体的售卖状态 由前端修改并返回，该方法传入的status是 修改之后的售卖状态，可以直接根据一个或多个菜品id进行查询并修改售卖即可
        log.info("菜品状态status：{}，需要修改的ids：{}",status,ids);
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ids!=null,Dish::getId,ids);
        List<Dish> dishList = dishService.list(queryWrapper);

        if (dishList != null){
            for (Dish dish : dishList) {
                dish.setStatus(status);
                dishService.updateById(dish);
            }
            return R.success("菜品的售卖状态已更改！");
        }
        return R.error("售卖状态不可更改,请联系管理员或客服！");
    }

   /* @GetMapping("/list")
    public R<List<Dish>> queryDishList(Dish dish){
        log.info("dish的");
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        // 模糊搜索条件
        if (dish.getName()!=null) {
            queryWrapper.and(c -> c.like(dish.getName()!=null,Dish::getName,dish.getName()));
        }

        // status 为 1: 还在售卖的菜品
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);
        return R.success(list);

    }*/

    @GetMapping("/list")
    public R<List<DishDto>> queryDishList(Dish dish){
        log.info("dish的");
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        // 模糊搜索条件
        if (dish.getName()!=null) {
            queryWrapper.and(c -> c.like(dish.getName()!=null,Dish::getName,dish.getName()));
        }

        // status 为 1: 还在售卖的菜品
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtoList = list.stream().map((item)->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            //获取categoryId
            Long categoryId = item.getCategoryId();
            //根据categoryId查询菜品分类的categoryName
            Category category = categoryService.getById(categoryId);
            if (category!=null){
                String categoryName = category.getName();
                //将查询到的categoryName封装到dishDto的categoryName
                dishDto.setCategoryName(categoryName);
            }
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
            lqw.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavors = dishFlavorService.list(lqw);

            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());
        return R.success(dishDtoList);

    }
}
